<template>
  <div class="custom-integralType-container personalIntegralType-container-mar">
    <div class="custom-search-container">
      <div class="custom-search-item">
        <span class="custom-searchInpt-label">部门类型：</span>
        <el-select v-model="selectForm.deptCategoryId" clearable placeholder="请选择">
          <el-option v-for="(item,index) in allDeptCateData" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </div>
      <div class="custom-search-item">
        <span class="custom-searchInpt-label">部门层级：</span>
        <el-select v-model="selectForm.deptLevel" clearable placeholder="请选择">
          <el-option v-for="(item,index) in levelData" :key="index" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </div>
      <div class="custom-search-item">
        <span class="custom-searchInpt-label">名称：</span>
        <el-input v-model="selectForm.departmentName" clearable autocomplete="off" class="dzy-custom-input"></el-input>
      </div>
      <div class="custom-search-item">
        <span class="custom-searchInpt-label">开始时间：</span>
        <el-date-picker
          v-model="selectForm.startDate"
          type="date"
          value-format="timestamp"
          format="yyyy 年 MM 月 dd 日"
          placeholder="选择日期"
          :picker-options="dataPickerBeforeTodayOptions">
        </el-date-picker>
      </div>
      <div class="custom-search-item">
        <span class="custom-searchInpt-label">结束时间：</span>
        <el-date-picker
          v-model="selectForm.endDate"
          type="date"
          value-format="timestamp"
          format="yyyy 年 MM 月 dd 日"
          placeholder="选择日期"
          :picker-options="dataPickerBeforeTodayOptions">
        </el-date-picker>
      </div>
      <div class="custom-search-item custom-search-btn">
        <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
      </div>
    </div>
    <div id="integralTypeEchart"></div>
    <span class="iconfont el-icon-extend-shangyibusvg" id="lastStep" @click="lastStepClickEvt"></span>
    <span class="iconfont el-icon-extend-xiayibu" id="nextStep" @click="nextStepClickEvt"></span>
  </div>
</template>

<script>
import exportExcl from '@/assets/img/exportExcl.png'
import {getToken} from '@/utils/LocalDataUtil'
import {listDeptCate} from '@/http/AppApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findDeptIntegralAnalysis, findIntegralTypeList, getExportFileUrl} from '@/http/integralApi'
export default {
  data () {
    return {
      legendIntegralData: [],
      xAxisVillagesData: [],
      legendSelectData: [],
      seriesData: [],
      colors: [
        '#8861d6', '#ef8824', '#f465ae', '#617eff', '#ffd818', '#5fdcc0', '#f48919', '#7cd21f',
        '#4a90e2', '#f3b100', '#ff6b5c', '#3f50ac', '#faa123', '#36c2cf', '#5472ea'
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      selectForm: {
        offset: 0
      },
      currentPage: 1,
      totalPage: 0,
      allDeptCateData: [],
      levelData: [],
      dataViewData: {}
    }
  },
  mounted () {
    this.getIntegralTypeList()
    this.getDeptIntegralList()
    this.getSelectDeptCateData()
    this.levelData = getDictDataOption('层级')
  },
  methods: {
    resetSeriesData () {
      if (this.seriesData.length > 0) {
        this.xAxisVillagesData = []
        for (let i = 0; i < this.seriesData.length; i++) {
          this.seriesData[i].data = []
        }
      }
    },
    lastStepClickEvt () {
      if (this.currentPage === 1) return ''
      this.resetSeriesData()
      this.currentPage -= 1
      this.selectForm.offset = (this.currentPage - 1) * 10
      this.getDeptIntegralList(this.selectForm)
    },
    nextStepClickEvt () {
      if (this.currentPage === this.totalPage) return ''
      this.resetSeriesData()
      this.currentPage += 1
      this.selectForm.offset = (this.currentPage - 1) * 10
      this.getDeptIntegralList(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getDeptIntegralList(this.selectForm)
    },
    getSelectDeptCateData () {
      listDeptCate().then(resp => {
        if (resp.code && resp.code === '200') {
          this.allDeptCateData = resp.data
        }
      })
    },
    getIntegralTypeList () {
      let m = this
      findIntegralTypeList('02').then(resp => {
        if (resp.code && resp.code === '200') {
          if (resp.data instanceof Array && resp.data.length > 0) {
            for (let i = 0; i < resp.data.length; i++) {
              m.legendIntegralData.push(resp.data[i].name)
              let n = i + 1
              let seriesDataItem = {}
              seriesDataItem.name = resp.data[i].name
              seriesDataItem.type = 'bar'
              seriesDataItem.itemStyle = {
                color: m.colors[n % m.colors.length]
              }
              seriesDataItem.data = []
              m.seriesData.push(seriesDataItem)
            }
          }
        }
      })
    },
    getDeptIntegralList (param) {
      let m = this
      findDeptIntegralAnalysis(param).then(resp => {
        if (resp.code && resp.code === '200') {
          m.xAxisVillagesData = []
          let res = parseInt(resp.data.total / 10)
          m.totalPage = resp.data.total / 10 > res ? res + 1 : res
          let deptIntegralData = resp.data.items
          if (deptIntegralData instanceof Array && deptIntegralData.length > 0) {
            for (let i = 0; i < deptIntegralData.length; i++) {
              m.xAxisVillagesData.push(deptIntegralData[i].departmentName)
              if (deptIntegralData[i].scoreTypeGrade) {
                for (let key in deptIntegralData[i].scoreTypeGrade) {
                  for (let j = 0; j < m.seriesData.length; j++) {
                    if (m.seriesData[j].name === key) {
                      m.seriesData[j].data.push(deptIntegralData[i].scoreTypeGrade[key])
                    }
                  }
                }
              }
            }
          }
          m.loadIntegralTypeEchart()
        }
      })
    },
    getDataViewData (integralTypeEchart) {
      this.dataViewData = {
        show: true,
        readOnly: true,
        optionToContent: function (integralTypeEchart) {
          // 坐标数据
          let axisData = integralTypeEchart.xAxis[0].data
          // 柱状图数据
          let series = integralTypeEchart.series
          // 表头
          let tdHeads = '<td style="padding: 10px 30px;background: #cccccc;">部门名称</td>'
          // 数据
          let tdBodys = ''
          series.forEach(function (item) {
            // 组装表头
            tdHeads += `<td style="padding: 10px 30px;background: #cccccc;">${item.name}</td>`
          })
          let table = `<table border="1" style="margin-left: 20px;border-collapse:collapse;font-size:14px;text-align:center"><tbody><tr>${tdHeads} </tr>`
          for (let i = 0, l = axisData.length; i < l; i++) {
            for (let j = 0; j < series.length; j++) {
              // 组装表数据
              tdBodys += `<td>${series[j].data[i]}</td>`
            }
            table += `<tr><td style="padding: 10px 30px">${axisData[i]}</td>${tdBodys}</tr>`
            tdBodys = ''
          }
          table += '</tbody></table>'
          return table
        }
      }
    },
    loadIntegralTypeEchart () {
      let m = this
      let integralTypeEchart = this.$echarts.init(document.getElementById('integralTypeEchart'))
      this.getDataViewData(integralTypeEchart)
      integralTypeEchart.setOption({
        color: ['#3398DB'],
        title: { text: '2019乡镇积分对比', x: 'center', top: 5 },
        tooltip: { trigger: 'axis', axisPointer: { type: 'line' } },
        grid: { left: '3%', right: '4%', bottom: '12%', containLabel: true },
        toolbox: {
          feature: {
            dataView: m.dataViewData,
            magicType: {show: true, type: ['line', 'bar']},
            restore: {show: true},
            saveAsImage: {show: true},
            myTool1: {
              show: true,
              title: '导出Excl',
              icon: 'image://' + exportExcl,
              onclick: () => {
                let token = getToken()
                let arr = []
                arr = m.legendSelectData.length === 0 ? m.legendIntegralData : m.legendSelectData
                let param = ''
                for (const key in m.selectForm) {
                  if (m.selectForm.hasOwnProperty(key)) {
                    param += '&' + key + '=' + m.selectForm[key]
                  }
                }
                let path = getExportFileUrl(true) + '?token=' + token + '&scoreTypeList=' + arr + param + '&t=' + Math.random()
                window.location.href = path
                return ''
              }
            }
          },
          right: 20,
          top: 10
        },
        legend: { data: m.legendIntegralData, bottom: 14 },
        xAxis: [{
          type: 'category',
          data: m.xAxisVillagesData,
          axisLabel: {
            interval: 0,
            rotate: 28
          }
        }],
        yAxis: [{ type: 'value', name: '积分类型总数' }],
        series: m.seriesData
      })
      integralTypeEchart.on('legendselectchanged', function (obj) {
        m.legendSelectData = []
        for (const key in obj.selected) {
          if (obj.selected.hasOwnProperty(key)) {
            if (obj.selected[key]) {
              m.legendSelectData.push(key)
            }
          }
        }
      })
    }
  }
}
</script>

<style>
#integralTypeEchart{
  width: 94%;
  height: 520px;
  margin: 0 auto;
}
</style>
